

$(function() {
	console.log('公司类别：'+'{$company.company_mode}')
	var myScroll2 = new IScroll('#carlist', {
		mouseWheel: true,
		scrollX: true,
		scrollY: false,
		disableMouse: true,
		disablePointer: true,
		scrollbars: 'custom',
		interactiveScrollbars: true,
	});
	$("#loading-first").fadeOut(500);
	var allcar = '';
	var cardata = {};
	var page = 1;
	var beidouload = layer.load(0, {
		shade: [0.1, '#fff'] //0.1透明度的白色背景
	});
	//车辆详情
	var tddata=[
			{
				key:'number',
				type:1,
				url:''
			},{
				key:'brandname',
				type:1,
				id:137
			},{
				key:'car_type_name',
				type:1,
				url:''
			},{
				key:'company_name',
				type:1,
				url:''
			},{
				key:'register_time',
				type:1,
				url:''
			},{
				key:'state2',
				type:1,
				url:''
			}];
	var addoperation = `<td class='operation'>
			<div class="tpl-table-black-operation">
				<a class="details" href="javascript:;">
					<i class="am-icon-pencil"></i> 详情
				</a>
				<a class="change" href="javascript:;">
					<i class="am-icon-pencil"></i> 编辑
				</a>
				<a href="javascript:;" class="tpl-table-black-operation-del delete-list" data-method="delete">
					<i class="am-icon-trash"></i> 删除
				</a>
				<a class="showTrack" data-method="showmap" data-location="">
					<i class="am-icon-map"></i> 当前位置
				</a>
			</div>
		</td>`;
	//带有车辆经纬度
//	$.ajax({
//		type: "post",
//		url: "{:url('/adminapi/beidou/cars')}",
//		data: {},
//		success: function(res1) {
//			layer.close(beidouload)
//			console.log(res1)
//
//			$('.add_car').on('click', function() {
//				window.location.href = '{:url("add")}'
//			})
//			if(res1.code == 1) {
//				allcar = res1.data
//			} else {
//
//				Err(res1.msg)
//			}
//		},
//		error: function() {
//			layer.close(beidouload)
//			Err('请求失败')
//			$("#loading-first").fadeOut(500);
//		}
//	})
	cardata = {
		page: page,
		pagenum: 10,
		where_json: JSON.stringify({
			{if $company.company_mode==1}
			company_id: ['in', $('.company_all_id').val()]
			{elseif  $company.company_mode==2/}
			"entrust_company_id|company_id": ['in', $('.company_all_id').val()]
			{/if}
		})
	}

	ajaxcar(cardata)
	
	$('.search').on('click', function() {
		page=1
		cardata.page = page;
		cardata.pagenum = 10;
		
		var where_json1={
			number: ['like', '%' + $('.car_number').val() + '%']
		}
		{if $company.company_mode==1}
			if($('.entrust').val()==1){
				where_json1.company_id= ['in', $('.company_all_id').val()];
				where_json1.entrust_company_id= ['in', '0']
			}else if($('.entrust').val()==2){
				where_json1.company_id= ['in', $('.company_all_id').val()];
				where_json1.entrust_company_id= ['gt',0]
			}else{
				where_json1.company_id= ['in', $('.company_all_id').val()];
			}
		{elseif  $company.company_mode==2/}
			
			if($('.entrust').val()==1){
				where_json1.company_id= ['in', $('.company_all_id').val()];
			}else if($('.entrust').val()==2){
				where_json1.entrust_company_id= ['in',$('.company_all_id').val()];
				where_json1.company_id= ['neq',$('.company_all_id').val()];
			}else{
				where_json1['entrust_company_id|company_id']=['in', $('.company_all_id').val()];
			}
		
		{/if}
		cardata.where_json = JSON.stringify(where_json1)
		ajaxcar(cardata)
	})
	$('.previous').on('click', function() {
		page-=1
		$('.page').html(page)
		cardata.page=page
		 ajaxcar(cardata) 
	})
	$('.next').on('click', function() {
		page+=1
		$('.page').html(page)
		cardata.page=page
		 ajaxcar(cardata) 
	})
	$('.pagebtn').on('click', function() {
		page=$('.page-in').val()
		$('.page').html($('.page-in').val())
		cardata.page=page
		 ajaxcar(cardata) 
	})
	
	function ajaxcar(cardata) {
		Load()
		var carlist = "";
		carlist += `<li class="dwd_car_list">
					<div class="add_car" style="height: 150px;width: 200px;text-align: center;">
						<span class="am-icon-plus-square-o" style="line-height: 150px;font-size: 60px;font-weight: 900;"></span>
					</div>
				</li>`
		$.ajax({
			type: 'post',
			data: cardata,
			url: '{:url("/adminapi/Car/carList")}',
			success: function(res) {
				Load(1)
				
				console.log(res);
				var unit_car = res.data;
				eachar(unit_car)
				for(var i=0;i<res.data.length;i++){
					if(res.data[i].state==1){
						res.data[i].state2='启用'
					}else{
						res.data[i].state2='禁用'
					}
					res.data[i].brandname=''
					if(res.data[i].name){
//						res.data[i].brandname+=res.data[i].name
						if(res.data[i].model_name){
							res.data[i].brandname+=res.data[i].model_name
							if(res.data[i].series_name){
								res.data[i].brandname+=res.data[i].series_name
							}
						}
					}else{
						res.data[i].brandname='暂未获取到车型'
					}
				}
				console.log(unit_car.length);
				$('tbody').html(tbodymainf2(res.data, 1, tddata, addoperation, 'car_id'))
				console.log(pagechang1(res.count, 10, page))
				if(pagechang1(res.count, 10, page)){
					$('.pagination').html(pagechang1(res.count, 10, page))
					
				}else{
					$('.pagination').html(' ')
				}
				myScroll.refresh()
				$('.laquo').on('click', function() {
					page-=1
					cardata.page=page
					ajaxcar(cardata)
				})
				$('.pageli').on('click', function() {
					page=$(this).html()
					cardata.page=page
					ajaxcar(cardata)
				})
				$('.raquo').on('click', function() {
					page+=1
					cardata.page=page
					ajaxcar(cardata)
				})
				$('.add_car').unbind();
				//导出
				$('.export').on('click', function() {
					
					// var dadad={
					// 	where_json:JSON.stringify({})
					// }
					var tddata=[
					{key:'number'},
					{key:'car_type_name'},
					{key:'name'},
					{key:'engine_no'},
					{key:'displacement'},
					{key:'source'},
					{key:'energy_type'},
					{key:'buy_money'},
					{key:'buy_date'},
					{key:'colour'},
					{key:'car_age'},
					{key:'mileage'},
					{key:'gearbox_type'},
					{key:'carry'},
					{key:'structure'},
					{key:'prop'},
					{key:'driving_license_issued'},
					{key:'buy_money'},
					{key:'company_name'},
					{key:'entrust_use_id'},
					{key:'entrust_rental_id'},
					{key:'rent_company'}];
					
					exports(res,tddata,cardata,"{:url('adminapi/Car/downLoadCarList')}")
				})
				//显示当前位置
				$('.showTrack').on('click',function(e){
					console.log(66)
					var car_id=$(this).closest('tr').data('id')
					var that = this
					popup(this)
			
					var map = new AMap.Map('showlocation', {
						resizeEnable: true,
						zoom: 14,
						center: [118.57, 24.82]
					});
					var carlocload = layer.load(0, {
						shade:  [0.3,'#fff']
					});
					console.log(encodeURI($(that).closest('tr').data('number')))
					AMapUI.loadUI(['overlay/SimpleMarker'], function(SimpleMarker) {
						$.ajax({
							type: 'post',
							url: '{:url("admin/beidou/cars")}',
							data: {
								car_id: car_id
							},
							success: function(res) {
								console.log(res)
								layer.close(carlocload);
								console.log(res)
								if(res.code == 1) {
									if(res.data[0]) {
										if(res.data[0].loc) {
											if(res.data[0].loc[0]) {
												carloc = res.data[0].loc
												 map.setZoomAndCenter(14,carloc);
												driverloc = new SimpleMarker({
													//普通文本
													iconStyle: {
														src: '{$static_dir}/assets/img/car-red.png',
														style: {
															width: '15px',
															height: '30px'
														}
													},
													position: carloc,
													cont: {}
												});
												console.log('放入地图')
												driverloc.setMap(map);
												AMap.plugin('AMap.Geocoder', function() {
													geocoder = new AMap.Geocoder({
														city: "010" //城市，默认：“全国”
													});
													geocoder.getAddress(carloc, function(status, result) {
														if(status === 'complete' && result.info === 'OK') {
															//获得了有效的地址信息:
															//即，
															var infoWindow = new AMap.InfoWindow({
														       content: result.regeocode.formattedAddress,  //使用默认信息窗体框样式，显示信息内容
														        offset: new AMap.Pixel(0, -25)
															});
															infoWindow.open(map, carloc);
															
														} else {
															
														}
													});
													$(that).on('mouseout', function() {
//														layer.close(tips)
													})
												})
												
											} else {
												Err('暂无定位')
											}
										} else {
											Err('暂无定位')
										}
									} else {
										Err('暂无定位')
									}
								} else {
									Err('暂无定位')
								}
							}
						});
					});
				})
				//车辆编辑
				$('.change').on('click',function(e){
					var car_id=$(this).closest('tr').data('id')
					window.location.href="{:url('/unit/car/edit')}?car_id="+car_id
				})
				//车辆详情
				$('.details').on('click',function(e){
					var car_id=$(this).closest('tr').data('id');
					window.location.href="{:url('/unit/car/details')}?car_id="+car_id
				})
				//车辆删除
				$('.delete-list').on('click',function(e){
					e.stopPropagation();
					var car_id=$(this).closest('tr').data('id')
					
					layer.open({
						type: 1,
						title: false,
						id: "delect" ,
						content: "<div class='am-vertical-align-middle' style='width:100%;text-align:center'>是否删除</div>",
						btn: ['确定', '取消'],
						btnAlign: 'c' ,
						shade: 0 ,
						yes: function() {
							var forbiddenload = layer.load(1, {
								shade: [0.1, '#fff'] //0.1透明度的白色背景
							});
							
							$.ajax({
								method: "POST",
								url: "{:url("adminapi/Car/delete")}",
								data: {
									car_ids:car_id
								},
								success: function(res) {
									if(res.code == 1) {
										layer.closeAll();
										 ajaxcar(cardata) 
									} else if(res.code == 0) {
										layer.close(forbiddenload);
										Err(res.msg ? res.msg : '操作失败，稍候再试');
									}
		
								}
							});
						},
						btn2: function() {
							layer.closeAll();
						}
					});
				})
				$('.add_car').on('click', function() {
					window.location.href = '{:url("add")}';
				})
				
//				myScroll2.refresh()
				
				
			},
			error: function() {
				Load(1)
				$("#loading-first").fadeOut(500);
			}
		});

	}


	function eachar(unit_car) {
		console.log(unit_car)
		//百度echar
		if(unit_car.length > 0) {
			var car_cost = echarts.init(document.getElementById('car_cost'));
			car_cost_op = {
				tooltip: {
					trigger: 'item',
					formatter: "{a} <br/>{b}: {c} ({d}%)"
				},
				legend: {
					orient: 'vertical',
					x: 'left',
					data: ['维修保养', '加油', '保险', '年检']
				},
				series: [{
					name: '订单数量',
					type: 'pie',
					radius: ['50%', '70%'],
					avoidLabelOverlap: false,
					label: {
						normal: {
							show: false,
							position: 'center'
						},
						emphasis: {
							show: true,
							textStyle: {
								fontSize: '24',
								fontWeight: 'bold'
							}
						}
					},
					labelLine: {
						normal: {
							show: false
						}
					},
					data: [{
							value: 14000,
							name: '维修保养'
						},
						{
							value: 20000,
							name: '加油'
						},
						{
							value: 6000,
							name: '保险'
						},
						{
							value: 20000,
							name: '年检'
						},

					]
				}]
			};
			car_cost.setOption(car_cost_op);
			var kilometre = echarts.init(document.getElementById('kilometre'));
			var car_number_list = [];
			var car_main_list = [];
			var allmileage = 0;
			var carlength=0;
			if(unit_car.length>10){
				carlength=0
			}else{
				carlength=unit_car.length
			}
			for(caridx = 0; caridx < carlength; caridx++) {
				allmileage = allmileage + (unit_car[caridx].mileage - 0)
				car_number_list.push(unit_car[caridx].number)
				car_main_list.push({
					value: unit_car[caridx].mileage,
					name: unit_car[caridx].number
				})
			}
			$('.allmileage').html(`${allmileage}公里`)
			kilometre_op = {
				tooltip: {
					trigger: 'item',
					formatter: "{a} <br/>{b}: {c} ({d}%)"
				},
				legend: {
					orient: 'vertical',
					x: 'left',
					data: car_number_list
				},
				series: [{
					name: '订单数量',
					type: 'pie',
					radius: ['50%', '70%'],
					avoidLabelOverlap: false,
					label: {
						normal: {
							show: false,
							position: 'center'
						},
						emphasis: {
							show: true,
							textStyle: {
								fontSize: '24',
								fontWeight: 'bold'
							}
						}
					},
					labelLine: {
						normal: {
							show: false
						}
					},
					data: car_main_list
				}]
			};
			kilometre.setOption(kilometre_op);

			var wear = echarts.init(document.getElementById('wear'));

			wear_op = {
				xAxis: {
					type: 'category',
					data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
				},
				yAxis: {
					type: 'value'
				},
				series: [{
					data: [120, 200, 150, 80, 70, 110, 130],
					type: 'bar'
				}]
			};
			wear.setOption(wear_op);
			var analyze_cost = echarts.init(document.getElementById('analyze_cost'));
			analyze_cost_op = {
				xAxis: {
					type: 'category',
					data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
				},
				yAxis: {
					type: 'value'
				},
				series: [{
					data: [120, 200, 150, 80, 70, 110, 130],
					type: 'bar'
				}]
			};
			analyze_cost.setOption(analyze_cost_op);
		} else {
			$('.allmileage').html(`0公里`)
			$('.carcost').html(`0元`)
			$('#car_cost').html('该单位无所属车辆')
			$('#car_cost').css('text-align', 'center')
			$('#kilometre').html('该单位无所属车辆')
			$('#kilometre').css('text-align', 'center')
			$('#wear').html('该单位无所属车辆')
			$('#wear').css('text-align', 'center')
			$('#analyze_cost').html('该单位无所属车辆')
			$('#analyze_cost').css('text-align', 'center')
		}
	}
})